<?php 

class Silk_Pms_Adminhtml_ActivityController extends Mage_Adminhtml_Controller_Action
{
	protected function _initAction()
	{
		$this->loadLayout()->_setActiveMenu("pms/items")
			->_addBreadcrumb(Mage::helper("adminhtml")->__("活动管理"),Mage::helper("adminhtml")->__("活动管理列表"));
		
		return $this;
	}


	public function indexAction()
    {
		$this->_initAction()->renderLayout();
	}


	public function editAction()
    {
		$id     = $this->getRequest()->getParam('id');
		$model  = Mage::getModel('pms/activity')->load($id);

		if ($model->getId() || $id == 0) {
			$data = Mage::getSingleton('adminhtml/session')->getFormData(true);

			if (!empty($data)) {
				$model->setData($data);
			}

			Mage::register('activity_data', $model);

			$this->loadLayout();
			$this->_setActiveMenu('pms/items');

			$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
			$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));

			$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

			$this->_addContent($this->getLayout()->createBlock('pms/adminhtml_activity_edit'))
				->_addLeft($this->getLayout()->createBlock('pms/adminhtml_activity_edit_tabs'));

			$this->renderLayout();
		} else {
			Mage::getSingleton('adminhtml/session')->addError(Mage::helper('pms')->__('Item does not exist'));
			$this->_redirect('*/*/');
		}
	}


	public function newAction()
    {
		$this->_forward('edit');
	}


    /**
     * save template all content
     */
	public function saveAction()
    {
        $image    = $_FILES["image"];
        $imagearr = $this->getImage($image);
        $upload   = Mage::helper("pms/fileupload");
        $images   = $upload->upload($imagearr, 'activity');
		$data     = $this->getRequest()->getPost();
        unset($data['form_key']);

		$model = Mage::getModel("pms/activity")->load($data['id']);
		if(!empty($data['defaultimg'])){
			foreach($images as $k => $v){
				$data['form_data']['image'][$k] = '';
			}
		}else{
			if($model && $model->getId() && $model->getFormData()){
				$olddata   = $model->getFormData();
				$oldresult = json_decode($olddata, true);
				$oldimage  = $oldresult["image"];
				if(count($images)){
					foreach ($images as $key => $value) {
						if($value){
							$images[$key] = $value;
						}else{
							$images[$key] = $oldimage[$key];
						}
					}
				}else{
					$images = $oldimage;
				}
			}

			foreach($images as $k => $v){
				$data['form_data']['image'][$k] = $v;
			}

		}

		if(!isset($data['form_data']['sku1'])){
			$data['form_data']['sku1'] = '';
		}
		if(!isset($data['form_data']['sku2'])){
			$data['form_data']['sku2'] = '';
		}
		if(!isset($data['form_data']['sku3'])){
			$data['form_data']['sku3'] = '';
		}
		if($data[images]){
			foreach($data['images'] as $k=>$v){
				if($v==1){
					$data['form_data']['image'][$k]='';
				}
			}
		}


        $tmp = json_encode($data['form_data']);
        $data['form_data'] = $tmp;

		if ($data) {
			$model = Mage::getModel('pms/activity');
			$model->setData($data)
				->setId($this->getRequest()->getParam('id'));
//			$model->setName($data['name'])
//                ->setAdminId($data['admin_id'])
//                ->setStatus($data['status'])
//                ->setStartAt($data['start_at'])
//                ->setEndAt($data['end_at'])
//                ->setDescription($data['description'])
//                ->setTemplateId($data['template_id'])
//                ->setFormData($data['form_data'])
//				->setId($this->getRequest()->getParam('id'));

			try {
				if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
					$model->setCreatedTime(now())
						->setUpdateTime(now());
				} else {
					$model->setUpdateTime(now());
				}

				$model->save();
				Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('pms')->__('保存成功'));
				Mage::getSingleton('adminhtml/session')->setFormData(false);

				if ($this->getRequest()->getParam('back')) {
					$this->_redirect('*/*/edit', array('id' => $model->getId()));
					return;
				}
				$this->_redirect('*/*/edit', array('template_id' => $model->getTemplateId(),'id' => $model->getId()));
				return;
			} catch (Exception $e) {
				Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
				Mage::getSingleton('adminhtml/session')->setFormData($data);
				$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
				return;
			}
		}
		Mage::getSingleton('adminhtml/session')->addError(Mage::helper('pms')->__('保存失败'));
		$this->_redirect('*/*/');
	}

    /**
     * @param $image image's name
     * @return mixed back to image's  url
     */
    public function getImage($image)
    {
        foreach ($image as $key => $value) {
            foreach ($value as $k => $v) {
                $imagearr[$k][$key]=$v[0];
            }
        }
        return $imagearr;

    }

	public function deleteAction()
    {
		if( $this->getRequest()->getParam('id') > 0 ) {
			try {
				$model = Mage::getModel('pms/activity');

				$model->setId($this->getRequest()->getParam('id'))
					->delete();

				Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('删除成功'));
				$this->_redirect('*/*/');
			} catch (Exception $e) {
				Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
				$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
			}
		}
		$this->_redirect('*/*/');
	}


	public function massDeleteAction()
    {
		$activityIds = $this->getRequest()->getParam('pms');
		if(!is_array($activityIds)) {
			Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
		} else {
			try {
				foreach ($activityIds as $activityId) {
					$activity = Mage::getModel('pms/activity')->load($activityId);
					$activity->delete();
				}
				Mage::getSingleton('adminhtml/session')->addSuccess(
					Mage::helper('adminhtml')->__(
						'Total of %d record(s) were successfully deleted', count($activityIds)
					)
				);
			} catch (Exception $e) {
				Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
			}
		}
		$this->_redirect('*/*/index');
	}


	public function massStatusAction()
	{
		$activityIds = $this->getRequest()->getParam('pms');
		if(!is_array($activityIds)) {
			Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
		} else {
			try {
				foreach ($activityIds as $activityId) {
					$activity = Mage::getSingleton('pms/activity')
						->load($activityId)
						->setStatus($this->getRequest()->getParam('status'))
						->setIsMassupdate(true)
						->save();
				}
				$this->_getSession()->addSuccess(
					$this->__('Total of %d record(s) were successfully updated', count($activityIds))
				);
			} catch (Exception $e) {
				$this->_getSession()->addError($e->getMessage());
			}
		}
		$this->_redirect('*/*/index');
	}



	protected function _isAllowed()
	{
		return Mage::getSingleton('admin/session')->isAllowed('pms/activity');
	}


    /**
     * select product info by Sku,productId,Name
     */
    public function productlistAction()
    {
        $result = array('error'=>true,'message'=>'');
        $sku = $this->getRequest()->getParam('sku');
        $productname = $this->getRequest()->getParam('productname');
        $productid = $this->getRequest()->getParam('productid');
        $websiteId = $this->getRequest()->getParam('websiteid');
        $website = Mage::getModel('core/website')->load($websiteId);
        $storeId = $website->getDefaultStore()->getId();

        $collection = Mage::getModel("catalog/product")->getCollection()->addAttributeToSelect('*');
        $collection->joinAttribute(
            'status',
            'catalog_product/status',
            'entity_id',
            null,
            'inner',
            $storeId
        );
        $collection->joinAttribute(
            'storename',
            'catalog_product/name',
            'entity_id',
            null,
            'inner',
            $storeId
        );
        $collection->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED));

        if($sku)
        {
            $collection->addAttributeToFilter('sku',array('eq'=>$sku));
        }
        if($productname)
        {
            $collection->addAttributeToFilter('storename',array('like'=>"%".$productname."%"));
        }
        if($productid){
            $collection->addAttributeToFilter('entity_id',array('eq'=>$productid));
        }

        $collection->setCurPage(1)->setPageSize(5);
        $isShowOutOfStock = Mage::getStoreConfigFlag('cataloginventory/options/show_out_of_stock');
        if(!$isShowOutOfStock)
        {
            Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);
        }

        if($collection->count())
        {
            $product = $collection->getFirstItem();
        }else{
            $result['message'] ="此商品在此站点不可用或不存在";
            echo  json_encode($result);
            return;
        }


        $datas = array();
        if($collection->count()){
            foreach($collection as $key => $product){
                $datas[] = array(
                    "product_id" => $product->getId(),
                    "name"       => $product->getStorename(),
                    "sku"        => $product->getSku(),
                    "image"      => $this->getImageId($product->getId()),
                    "description"=> $product->getDescription(),
                );
            }
        }else{
            $result['message'] = "商品在此站点不存在!请到该站点下操作";
            echo  json_encode($result);
            return;
        }

        $html ="";
        foreach($datas as $data){
            $html .= <<<HTML
				<tr class="parent" >
					<td style="border-bottom:1px solid #CBD3D4;width: 50px;" class="productids">{$data['product_id']}</td>
					<td style="border-bottom:1px solid #CBD3D4;width: 50px;" class="productsku">{$data['sku']}</td>
					<td style="border-bottom:1px solid #CBD3D4;width: 80px;" class="productnames">{$data['name']}</td>
					<td style="border-bottom:1px solid #CBD3D4;width: 150px;">{$data['image']}</td>
					<td style="border-bottom:1px solid #CBD3D4; width:60px;"><a href="#" class="remove">删除</a> | <a href="#" class="add">添加</a></td>
				 </tr>
HTML;
        }

        $result = array('error'=>false,'message'=>$html);
        echo json_encode($result);
    }



    /**
     * @param $id  productId
     * @return thumbnail url
     */
    public function getImageId($id)
    {
        try {

            $product = Mage::getModel('catalog/product')->load($id);

            $websiteId = Mage::getSingleton('admin/session')->getUser()->getWebsiteId();

            if($websiteId){
                $storeId = Mage::getModel('core/website')->load($websiteId)->getDefaultStore()->getId();
                $product = Mage::getModel('catalog/product')->setStoreId($storeId)->load($id);
                $productImg = Mage::helper('catalog/image')->init($product,'small_image')->resize(100);
            }else{
                $productImg = Mage::helper('catalog/image')->init($product,'small_image')->resize(100);
            }
        } catch (Exception $e){

            Mage::logException($e);

            $placeHolderImg = Mage::getStoreConfig("catalog/placeholder/small_image_placeholder");

            if(empty($placeHolderImg)){

                $productImg = "";

            }else{

                $productImg = Mage::getSingleton('catalog/product_media_config')->
                    getBaseMediaUrl(). '/placeholder/' . $placeHolderImg;

            }

        }


        return '<img src="'.$productImg.'">';
    }

    /**
     * pop up window to select product by sku or product name
     */
    public function addskuAction()
    {
        $this->loadLayout();
        $this->renderLayout();
    }


    public function massChangeStatusAction(){
    	try{
    		$ids = $this->getRequest()->getPost('pms', array());
    		$status = $this->getRequest()->getPost('status');
    		foreach ($ids as $id) {
    			$model = Mage::getModel("pms/activity")->load($id);
    			$model->setStatus($status);
    			$model->save();
    		}
    		Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("状态已修改"));
    	}
    	catch (Exception $e) {
    		Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
    	}
    	$this->_redirect('*/*/');
    }

}